<template>
  <view class="app-layout">
    <app-header :title="tit" />
    <view class="goods-container">
      <scroll-view scroll-y="true" style="height: 80vh">
        <view class="step-nav">
          <view class="step-item" :class="{ active: currentStep === 1 }">
            第一步：填写基础信息
          </view>
          <view class="step-item" :class="{ active: currentStep === 2 }">
            第二步：填写商品详情
          </view>
        </view>

        <view class="form-container">
          <u-form labelPosition="left" labelWidth="100px" :model="formData" ref="refFrom">
            <template v-if="currentStep == 1">
              <view class="info-tit"> 基本信息 </view>
              <view class="form-con">
                <uni-row :gutter="30">
                  <uni-col :span="12">
                    <u-form-item label="商品编码">
                      <uni-easyinput :maxlength="8" clearable v-model="formData.categoryName"
                        placeholder="不填写时，系统将默认生成商品SPU码">
                        <template #right>
                          <text class="suffix-num">0/8</text>
                        </template>
                      </uni-easyinput>
                    </u-form-item>
                  </uni-col>
                  <uni-col :span="12">
                    <u-form-item label="商品名称" required>
                      <uni-easyinput :maxlength="20" clearable v-model="formData.name" placeholder="请输入">
                        <template #right>
                          <text class="suffix-num">0/20</text>
                        </template>
                      </uni-easyinput>
                    </u-form-item>
                  </uni-col>
                  <uni-col :span="12">
                    <u-form-item label="商品分类" required>
                      <uni-data-picker :localdata="range" popup-title="请选择" @change="onchange" @nodeclick="onnodeclick"
                        v-model="formData.categoryId"></uni-data-picker>
                    </u-form-item>
                  </uni-col>
                  <uni-col :span="12">
                    <u-form-item label="展示排序">
                      <uni-easyinput placeholder="请输入" type="number" clearable
                        v-model="formData.sortOrder"></uni-easyinput>
                    </u-form-item>
                  </uni-col>
                  <uni-col :span="12">
                    <u-form-item label="发布场景" required>
                      <u-checkbox-group v-model="formData.sceneLabel" @change="checkboxChange">
                        <u-checkbox :customStyle="{ marginRight: '8px' }" label="门店自提" name="门店自提" />
                        <u-checkbox label="外卖配送" name="外卖配送" />
                      </u-checkbox-group>
                    </u-form-item>
                  </uni-col>
                  <uni-col :span="12">
                    <u-form-item label="配送方式">
                      <!-- <u-checkbox-group v-model="formData.deliveryMethod" @change="checkboxChange">
                        <u-checkbox shape="circle" label="商家配送" :name="0" />
                      </u-checkbox-group> -->
                      <u-radio-group v-model="formData.deliveryMethod">
                        <u-radio label="商家配送" :name="0" />
                      </u-radio-group>
                    </u-form-item>
                  </uni-col>
                  <uni-col :span="12">
                    <u-form-item label="制作时长">
                      <uni-easyinput placeholder="请输入" :maxlength="20" type="number" clearable
                        v-model="formData.productionTime">
                        <template #right>
                          <text class="suffix-txt">分钟</text>
                        </template>
                      </uni-easyinput>
                    </u-form-item>
                  </uni-col>
                  <uni-col :span="12">
                    <u-form-item label="商品状态">
                      <u-radio-group v-model="formData.isPublished">
                        <u-radio :customStyle="{ marginRight: '8px' }" label="在售" :name="1" />
                        <u-radio label="下架" :name="0" />
                      </u-radio-group>
                    </u-form-item>
                  </uni-col>
                </uni-row>
              </view>
              <view class="info-tit"> 价格设置 </view>
              <view class="form-con">
                <uni-row :gutter="30">
                  <uni-col :span="12">
                    <u-form-item label="商品规格">
                      <view class="specifications" @click="addSpecGroup"> 添加规格 </view>
                    </u-form-item>
                  </uni-col>
                  <!-- 无添加商品规格 -->
                  <template v-if="specGroups.length <= 0">

                    <uni-col :span="12">
                      <u-form-item label="零售价" required>
                        <uni-easyinput placeholder="请输入" type="digit" clearable v-model="formData.retailPrice">
                          <template #right>
                            <text class="suffix-txt">元</text>
                          </template>
                        </uni-easyinput>
                      </u-form-item>
                    </uni-col>
                    <uni-col :span="12">
                      <u-form-item label="市场价">
                        <uni-easyinput placeholder="请输入" type="digit" clearable v-model="formData.marketPrice">
                          <template #right>
                            <text class="suffix-txt">元</text>
                          </template>
                        </uni-easyinput>
                      </u-form-item>
                    </uni-col>
                    <uni-col :span="12">
                      <u-form-item label="成本价">
                        <uni-easyinput placeholder="请输入" type="digit" clearable v-model="formData.costPrice">
                          <template #right>
                            <text class="suffix-txt">元</text>
                          </template>
                        </uni-easyinput>
                      </u-form-item>
                    </uni-col>
                  </template>
                </uni-row>
                <uni-row>
                  <template v-if="specGroups.length > 0">
                    <view v-for="(group, groupIndex) in specGroups" :key="groupIndex" class="spec-group">
                      <view class="del-btn">
                        <u-button type="error" :plain="true" @click="removeSpecGroup(groupIndex)">- 删除规格</u-button>
                      </view>
                      <uni-row>
                        <uni-col :span="12">
                          <u-form-item label="规格名称">
                            <uni-easyinput placeholder="如：杯型、甜度" clearable v-model="group.specName"></uni-easyinput>
                          </u-form-item>
                        </uni-col>
                      </uni-row>

                      <uni-row>
                        <uni-col :span="24">
                          <u-form-item label="规格值">
                            <u-row>
                              <u-tag v-for="(value, valueIndex) in group.specValues" plain :key="valueIndex"
                                :text="value" size="medium" closable
                                @close="removeSpecValue(groupIndex, valueIndex)"></u-tag>
                              <uni-easyinput placeholder="请输入规格值" clearable v-model="group.tempValue"></uni-easyinput>
                              <u-button type="primary" :plain="true" text="+ 添加规格值" :disabled="!group.tempValue.trim()"
                                @click="addSpecValue(groupIndex)"></u-button>
                            </u-row>
                          </u-form-item>
                        </uni-col>
                      </uni-row>
                    </view>

                    <view class="generate-btn">
                      <view class="specifications" @click="generateSpecs"> 一键生成规格明细 </view>
                    </view>

                    <uni-row>
                      <uni-col :span="24">
                        <u-form-item label="规格明细">
                          <uni-row :gutter="10">
                            <uni-col :span="6">
                              <uni-easyinput placeholder="零售价" type="digit" clearable v-model="batchRetail">
                                <template #right>
                                  <text class="suffix-txt">元</text>
                                </template>
                              </uni-easyinput>
                            </uni-col>
                            <uni-col :span="6">
                              <uni-easyinput placeholder="市场价" type="digit" clearable v-model="batchMarket">
                                <template #right>
                                  <text class="suffix-txt">元</text>
                                </template>
                              </uni-easyinput>
                            </uni-col>
                            <uni-col :span="6">
                              <uni-easyinput placeholder="成本价" type="digit" clearable v-model="batchCost">
                                <template #right>
                                  <text class="suffix-txt">元</text>
                                </template>
                              </uni-easyinput>
                            </uni-col>
                            <uni-col :span="6">
                              <u-button type="primary" :plain="true" text="批量填写" @click="batchFill"></u-button>
                            </uni-col>
                          </uni-row>
                        </u-form-item>
                      </uni-col>
                    </uni-row>
                    <uni-table border stripe emptyText="暂无更多数据" v-if="show">
                      <!-- 表头行 -->
                      <uni-tr>
                        <uni-th width="100" align="left" v-for="(group, gIndex) in specGroups"
                          :key="gIndex">{{ group.specName }}</uni-th>
                        <uni-th width="250" align="left">SKU编码</uni-th>
                        <uni-th width="150" align="left"><text class="start">
                            *</text>零售价</uni-th>
                        <uni-th width="150" align="left">市场价</uni-th>
                        <uni-th width="150" align="left">成本价</uni-th>
                        <uni-th align="left" width="100">操作</uni-th>
                      </uni-tr>
                      <!-- 表格数据行 -->
                      <uni-tr v-for="(row, rIndex) in specsRows" :key="rIndex">
                        <uni-td v-for="(group, gIndex) in specGroups" :key="gIndex">
                          {{ row.specValueDtoList.find((item) => item.name === group.specName)?.value }}
                        </uni-td>
                        <uni-td>
                          <uni-easyinput :maxlength="11" placeholder="不填写时，系统将默认生成商品SKU码" clearable v-model="row.sku">
                            <template #right>
                              <text class="suffix-num">0/11</text>
                            </template>
                          </uni-easyinput>
                        </uni-td>
                        <uni-td>
                          <uni-easyinput placeholder="请输入" type="digit" clearable v-model="row.retailPrice">
                            <template #right>
                              <text class="suffix-txt">元</text>
                            </template>
                          </uni-easyinput>
                        </uni-td>
                        <uni-td>
                          <uni-easyinput placeholder="请输入" type="digit" clearable v-model="row.marketPrice">
                            <template #right>
                              <text class="suffix-txt">元</text>
                            </template>
                          </uni-easyinput>
                        </uni-td>
                        <uni-td>
                          <uni-easyinput placeholder="请输入" type="digit" clearable v-model="row.costPrice">
                            <template #right>
                              <text class="suffix-txt">元</text>
                            </template>
                          </uni-easyinput>
                        </uni-td>
                        <uni-td>
                          <u-icon name="trash" color="#EC3A4E" size="20"></u-icon>
                        </uni-td>
                      </uni-tr>
                    </uni-table>
                  </template>
                </uni-row>
                <uni-row>
                  <uni-col :span="12">
                    <u-form-item label="商品属性">
                      <!-- <u-input placeholder="请输入" :maxlength="20" clearable v-model="formData.categoryName">
                        <template #suffix>
                          <text class="suffix-txt">元</text>
                        </template>
                      </u-input> -->
                      <view class="specifications" @click="addAttribute('1')"> +选择属性 </view>
                    </u-form-item>
                  </uni-col>
                </uni-row>

                <uni-row>
                  <uni-col :span="24" :offset="3" v-if="attributeList.length > 0">
                    <uni-row :gutter="20" v-for="(item, index) in attributeList" :key="index">
                      <uni-col :span="6">
                        <view class="goods-name"> 属性名称 </view>
                        <view class="row-bot">
                          <uni-easyinput v-model="item.name" disabled></uni-easyinput>
                        </view>
                      </uni-col>
                      <uni-col :span="18">
                        <view class="goods-name"> 属性值 </view>
                        <uni-row :gutter="20">
                          <view class="marg-col row-bot">
                            <uni-col :span="10" v-for="(ite,ind) in item.attributeValue" :key="ind">
                              <uni-row :gutter="10">
                                <uni-col :span="20">
                                  <uni-easyinput v-model="ite.value" disabled></uni-easyinput>
                                </uni-col>
                                <uni-col :span="4">
                                  <image src="../../static/imgs/del.png" mode="" style="width: 30px; height: 30px"
                                    @click="deleteItem(index,ind)"></image>
                                </uni-col>
                              </uni-row>
                            </uni-col>
                          </view>

                        </uni-row>
                      </uni-col>
                    </uni-row>
                  </uni-col>
                </uni-row>
                <uni-row :gutter="30">
                  <uni-col :span="12">
                    <u-form-item label="商品加料">
                      <view class="specifications" @click="addAttribute('2')"> +选择加料 </view>
                    </u-form-item>
                  </uni-col>
                  <uni-col :span="12">
                    <u-form-item label="最多加几种">
                      <uni-easyinput placeholder="请输入" type="number" clearable v-model="formData.addonKind">
                        <template #right>
                          <text class="suffix-txt">种</text>
                        </template>
                      </uni-easyinput>
                    </u-form-item>
                  </uni-col>
                </uni-row>
                <uni-row v-if="feedingList.length>0">
                  <uni-col :span="24" :offset="3">
                    <uni-row :gutter="20">
                      <uni-col :span="7">
                        <view class="goods-name"> 加料商品名称 </view>
                      </uni-col>
                      <uni-col :span="7">
                        <view class="goods-name"> 价格 </view>
                      </uni-col>
                      <uni-col :span="7">
                        <view class="goods-name"> 最多加几份 </view>
                      </uni-col>
                    </uni-row>
                    <view class="row-bot" v-for="(itemF,indexF) in feedingList" :key="indexF">
                      <uni-row :gutter="20">
                        <uni-col :span="7">
                          <uni-easyinput v-model="itemF.name" disabled></uni-easyinput>
                        </uni-col>
                        <uni-col :span="7">
                          <uni-easyinput v-model="itemF.price" disabled></uni-easyinput>
                        </uni-col>
                        <uni-col :span="7">
                          <uni-easyinput placeholder="请输入" type="number" clearable v-model="itemF.num">
                            <template #right>
                              <text class="suffix-txt">份</text>
                            </template>
                          </uni-easyinput>
                        </uni-col>
                        <uni-col :span="3">
                          <image src="../../static/imgs/del.png" mode="" style="width: 30px; height: 30px"
                            @click="deleteFeeding(indexF)"></image>
                        </uni-col>
                      </uni-row>
                    </view>
                  </uni-col>
                </uni-row>
              </view>
              <view class="info-tit"> 商品图片</view>
              <view class="form-con">
                <uni-row :gutter="30">
                  <uni-col :span="24">
                    <view class="special-formitem">
                      <u-form-item label="商品主图" required class="img2">
                        <view class="upload1">
                          <u-upload imageMode="widthFix" :fileList="fileList1" @afterRead="afterRead"
                            @delete="deletePic" name="1" :maxCount="1" :previewFullImage="true"></u-upload>
                        </view>
                        <view style="color: #999999; font-size: 14px; margin-bottom: 4px">建议尺寸：800*800px，大小不超过3MB</view>
                      </u-form-item>
                    </view>
                  </uni-col>
                  <uni-col :span="24">
                    <view class="special-formitem">
                      <u-form-item label="详情图" required class="img2">
                        <view class="upload1">
                          <u-upload imageMode="widthFix" :fileList="fileList2" @afterRead="afterRead"
                            @delete="deletePic" name="2" :maxCount="6" :previewFullImage="true"></u-upload>
                        </view>
                        <view style="color: #999999; font-size: 14px; margin-bottom: 4px">
                          建议尺寸：800*800px，大小不超过3MB，最多上传6张。
                        </view>
                      </u-form-item>
                    </view>
                  </uni-col>
                  <!-- <uni-col :span="24">
                    <u-form-item label="详情图排序" v-if="fileList2.length>1">
                      <view class="preview-list">
                        <view class="preview-item" v-for="(img, index) in fileList2" :key="index">
                          <image :src="img.url" class="preview-img"></image>

                          <view class="operate-bar">
                            <uni-icons v-if="index!=0" type="left" class="operate-icon"
                              @click="sortImage(index, 'left')" color="#fff"></uni-icons>
                            <uni-icons v-if="index!=fileList2.length-1" type="right" class="operate-icon"
                              @click="sortImage(index, 'right')" color="#fff"></uni-icons>
                          </view>
                        </view>
                      </view>
                    </u-form-item>
                  </uni-col> -->

                </uni-row>
              </view>
            </template>
            <template v-if="currentStep == 2">
              <view class="form-con form-det">
                <view class="tit"> 商品详情 </view>
                <view class="editor-box">
                  <sp-editor :toolbar-config="{
                      excludeKeys: [
                        'direction',
                        'video',
                        'export',
                        'link',
                        'removeFormat',
                        'date',
                        'lineHeight',
                        'letterSpacing',
                        'listCheck',
                        'color',
                        'backgroundColor'
                      ],
                      iconSize: '18px',
                    }" @init="initEditor" @input="inputOver" @upinImage="upinImage" @overMax="overMax"
                    @addLink="addLink" @exportHtml="exportHtml"></sp-editor>
                </view>
              </view>
            </template>
          </u-form>
        </view>
      </scroll-view>
      <addPopup v-if="showPopup" :showPopup="showPopup" :titPopup="titPopup" @cancelPopup="cancelPopup"
        @surePopup="surePopup" :listPopup="listPopup" :valuePopup="valuePopup" />
    </view>
    <view class="submit_btncon">
      <view style="display: flex; margin: auto">
        <button class="submit_close" @click="close" v-if="currentStep == 1">取消</button>
        <button class="submit_close" @click="back" v-if="currentStep == 2">上一步</button>
        <button class="submit_btn" @click="submitReq" v-if="currentStep == 2">确认</button>
        <button class="submit_btn" @click="submit" v-if="currentStep == 1">下一步</button>
      </view>
    </view>
  </view>
</template>
<script setup>
  import {
    ref,
    watch,
    nextTick
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    getTreeCategory,
    updateSassCategoryById,
    addSassCategory,
    getAttributeDefinitions,
    getAddonOptions,
    addSassSpecs,
    findSpecsList,
    addProducts,
    updateProducts,
    getBySpuId
  } from '@/requests/apis/products'
  import {
    uploadImgApi
  } from '@/requests/apis/user'
  import
    addPopup
   from '@/components/addPopup/index.vue'
  const editorIns = ref(null)
  let spuId = ref()
  let tit = ref('新增商品')
  let show = ref(false)
  let showPopup = ref(false)
  let titPopup = ref()
  let listPopup = ref([])
  let attributeList = ref([])
  let feedingList = ref([])
  let valuePopup = ref()
  const currentStep = ref(1)
  const checkboxValue1 = ref('')
  const checkboxValue2 = ref('')
  const radiovalue1 = ref(1)
  let formData = ref({
    isPublished: 1,
    deliveryMethod: 0,
    sceneLabel: ['门店自提', '外卖配送']
  })
  const specGroups = ref([])
  const specsRows = ref([])
  let shuxingList = ref([])
  let jialiaoList = ref([])
  let fileList1 = ref([])
  let fileList2 = ref([])
  let range = ref([])
  // 批量填写的临时值
  const batchRetail = ref('') // 零售价
  const batchMarket = ref('') // 市场价
  const batchCost = ref('') // 成本价
  const isInitializing = ref(false); // 标记是否为初始化阶段
  watch(
    () => specGroups.value, // 监听的源（数组本身）
    (newVal, oldVal) => {
      console.log('数组发生变化：');
      console.log('新值：', newVal);
      console.log('旧值：', oldVal);
      console.log(isInitializing.value)
      if (!isInitializing.value) {
        console.log("zouzhelim1")
        show.value = false;
      }
    }, {
      deep: true, // 关键：开启深度监听，捕获内部元素变化
    }
  );
  onLoad((e) => {
    console.log(e, '1111111')
    getCategoryList()
    if (e.spuId) {
      spuId.value = e.spuId
      tit.value = '编辑分类'
      getDetail(e.spuId)
    }
    getList()
  })
  const getList = async () => {
    let res = await getAttributeDefinitions({
      page: 1,
      limit: 1000,
    })
    shuxingList.value = res.Result.records || [];
    let res2 = await getAddonOptions({
      page: 1,
      limit: 1000,
      keyword: ''
    })
    jialiaoList.value = res2.Result.records || [];
  }
  const getDetail = async (spuId) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    })
    let res = await getBySpuId({
      spuId
    })
    let data = res.Result;
    formData.value.spuId = data.spuId
    formData.value.name = data.name
    formData.value.name = data.name
    formData.value.categoryId = data.categoryId
    formData.value.sortOrder = data.sortOrder ? data.sortOrder : ''
    formData.value.sceneLabel = data.sceneLabel
    formData.value.deliveryMethod = data.deliveryMethod
    formData.value.isPublished = data.isPublished
    formData.value.productionTime = data.productionTime ? data.productionTime : ''
    formData.value.retailPrice = data.retailPrice
    formData.value.marketPrice = data.marketPrice
    formData.value.costPrice = data.costPrice
    formData.value.addonKind = data.addonKind
    formData.value.description = data.description
    console.log(data, 'data')
    // 规格
    if (data.specs) {
      isInitializing.value = true;
      specGroups.value = data.specs.map(spec => ({
        specName: spec.name,
        specValues: spec.specValues.map(item => item.value),
        tempValue: ''
      }));
      nextTick(() => {
        isInitializing.value = false;
      });
      console.log(specGroups.value, 'specGroups.value')
    }
    // 笛卡尔积
    if (data.skusList) {
      specsRows.value = data.skusList
      show.value = true
    }

    // 加料
    if (data.addonDtoList) {
      feedingList.value = data.addonDtoList
    }
    // 属性
    if (data.attributeDtoList) {
      attributeList.value = data.attributeDtoList
    }
    if (data?.mainImage) {
      const arr = data.mainImage.split(',')
      fileList1.value = arr.map((item) => {
        return {
          url: item,
          status: 'success',
        }
      })
    }
    if (data?.introImages) {
      const arr = data.introImages.split(',')
      fileList2.value = arr.map((item) => {
        return {
          url: item,
          status: 'success',
        }
      })
    }
    uni.hideLoading()
  }
  // 排序图片：左移/右移
  const sortImage = (index, direction) => {
    if (direction === 'left' && index > 0) {
      // 左移：和前一项交换
      const prev = fileList2.value[index - 1];
      fileList2.value[index - 1] = fileList2.value[index];
      fileList2.value[index] = prev;
    } else if (direction === 'right' && index < fileList2.value.length - 1) {
      // 右移：和后一项交换
      const next = fileList2.value[index + 1];
      fileList2.value[index + 1] = fileList2.value[index];
      fileList2.value[index] = next;
    }
  };
  const addAttribute = (type) => {
    if (type == '1') {
      let arr = []
      attributeList.value.forEach((item) => {
        arr.push(item.definitionId)
      })
      valuePopup.value = arr
      listPopup.value = shuxingList.value
    } else {
      let arr = []
      feedingList.value.forEach((item) => {
        arr.push(item.id)
      })
      valuePopup.value = arr
      listPopup.value = jialiaoList.value
    }
    showPopup.value = true
    titPopup.value = type
  }
  // 添加新的规格组
  const addSpecGroup = () => {
    specGroups.value.push({
      specName: '',
      specValues: [],
      tempValue: '',
    })
  }
  // 删除规格组
  const removeSpecGroup = (groupIndex) => {
    console.log('removeSpecGroup')
    specGroups.value.splice(groupIndex, 1)
  }
  // 添加规格值（去重校验）
  const addSpecValue = (groupIndex) => {
    const group = specGroups.value[groupIndex]
    const value = group.tempValue.trim()
    if (!value)
      return uni.showToast({
        title: '请输入有效规格值',
        icon: 'none',
      })
    if (group.specValues.includes(value))
      return uni.showToast({
        title: '该规格值已存在',
        icon: 'none',
      })

    group.specValues.push(value)
    group.tempValue = ''
  }

  // 删除单个规格值
  const removeSpecValue = (groupIndex, valueIndex) => {
    specGroups.value[groupIndex].specValues.splice(valueIndex, 1)
  }
  const generateSpecs = async () => {

    let res = await addSassSpecs({
      specs: specGroups.value
    })
    if (res) {
      let _res = await findSpecsList({
        specs: specGroups.value
      })
      console.log(_res.Result, '_res_res_res_res')
      specsRows.value = generateSpecCombinations(_res.Result)
      console.log('生成的规格数据：', specsRows.value) // 可查看控制台结构

      show.value = true
    }

  }
  // 生成笛卡尔积
  const generateSpecCombinations = (groups) => {
    if (groups.length === 0) return [];
    let combinations = groups[0].specValues.map(option => [{
      ...option,
      name: groups[0].name
    }]);
    for (let i = 1; i < groups.length; i++) {
      const temp = [];
      for (const combo of combinations) {
        for (const option of groups[i].specValues) {
          temp.push([
            ...combo,
            {
              ...option,
              name: groups[i].name
            }
          ]);
        }
      }
      combinations = temp;
    }
    return combinations.map(specItems => ({
      specValueDtoList: specItems,
      sku: '',
      retailPrice: '',
      marketPrice: '',
      costPrice: ''
    }));
  };
  // 批量填写逻辑：将批量值赋给所有规格行
  const batchFill = () => {
    specsRows.value.forEach((row) => {
      row.retailPrice = batchRetail.value
      row.marketPrice = batchMarket.value
      row.costPrice = batchCost.value
    })
  }
  // 商品属性 商品加料 确定
  const surePopup = (type, checkboxData) => {
    showPopup.value = false
    console.log(checkboxData, 'checkboxData', type)
    // 属性
    if (type == '1') {
      const invalidGoods = shuxingList.value.filter(item =>
        checkboxData.includes(item.definitionId)
      );
      attributeList.value = invalidGoods
    } else {
      const invalidGoods = jialiaoList.value.filter(item =>
        checkboxData.includes(item.id)
      );
      feedingList.value = invalidGoods;
      feedingList.value.forEach(item => {
        item['num'] = ''
      })
    }
  }
  // 删除商品加料
  const deleteFeeding = (index) => {
    feedingList.value.splice(index, 1);
  }
  // 删除商品属性
  const deleteItem = (attrIdx, valIdx) => {
    attributeList.value[attrIdx].attributeValue.splice(valIdx, 1);
    if (attributeList.value[attrIdx].attributeValue.length === 0) {
      attributeList.value.splice(attrIdx, 1);
    }
  }
  // 将扁平化数据还原为原始嵌套格式
  const restoreOriginalFormat = () => {
    const groupMap = {}

    flatList.value.forEach((item) => {
      const {
        definitionId,
        name,
        valueId,
        value
      } = item
      if (!groupMap[definitionId]) {
        groupMap[definitionId] = {
          definitionId,
          name,
          attributeValue: [],
        }
      }
      // 添加属性值
      groupMap[definitionId].attributeValue.push({
        definitionId,
        definitionValueId: valueId,
        value,
      })
    })
    return Object.values(groupMap)
  }
  const cancelPopup = (type) => {
    showPopup.value = false
  }
  // 递归转换函数
  const transformData = (list) => {
    return list.map((item) => {
      const transformed = {
        text: item.categoryName,
        value: item.categoryId,
      }
      if (item.children && item.children.length > 0) {
        transformed.children = transformData(item.children)
      }
      return transformed
    })
  }
  // 获取上级分类数据
  const getCategoryList = async () => {
    let res = await getTreeCategory({})
    let arr = res.Result || []
    const arr2 = transformData(arr)
    range.value = arr2
  }
  const afterRead = async (e) => {
    console.log(e, '1111111111')
    uni.showLoading({
      title: '加载中...',
      mask: true,
    })
    const res = await uploadImgApi(e.file)
    console.log(res, '1111111111')
    uni.hideLoading()
    if (res) {
      if (e.name === '1') {
        fileList1.value.push({
          status: 'success',
          url: res.Result,
        })
      } else {
        fileList2.value.push({
          status: 'success',
          url: res.Result,
        })
      }
    }
  }
  const deletePic = (e) => {
    if (e.name === '1') {
      fileList1.value.splice(e.index, 1)
    } else {
      fileList2.value.splice(e.index, 1)
    }
  }

  // 转换为后端需要的 skus 格式
  const convertToSkus = () => {
    const skus = specsRows.value.map(row => {
      return {
        specValueId: row.specValueDtoList.map(item => item.specValueId),
        retailPrice: Number(row.retailPrice) || null,
        marketPrice: Number(row.marketPrice) || null,
        costPrice: Number(row.costPrice) || null,
        skuId: row.skuId

      };
    });

    return skus;
  };

  const back = () => {
    currentStep.value = 1
  }


  const submit = () => {
    console.log(specsRows, 'specsRows')
    const valid = [{
        k: 'name',
        err: '请输入商品名称',
      },
      {
        k: 'categoryId',
        err: '请选择商品分类',
      },
      {
        k: 'sceneLabel',
        err: '请选择发布场景',
      },
      {
        k: 'deliveryMethod',
        err: '请选择配送方式',
      }
    ]
    let err = ''
    if (specGroups.value.length <= 0) {
      console.log("111111111111", formData.value.retailPrice)
      if (!formData.value.retailPrice) {
        err = '请输入零售价'
      }
    } else {
      if (specsRows.value.length <= 0) {
        err = '请点击一键生成规格明细去填写'
      }
    }
    if (!fileList1.value?.length) {
      err = '请上传商品主图'
    }
    if (!fileList2.value?.length) {
      err = '请上传商品分享图'
    }
    for (const item of specsRows.value) {
      if (item.retailPrice === '') {
        err = '请输入零售价'
        break
      }
    }
    for (let item of valid) {
      if (!formData.value[item.k] && formData.value[item.k] !== 0) {
        err = item.err
        break
      }
    }
    console.log(typeof(formData.value.addonKind),'formData.value.addonKind')
    if (formData.value.addonKind !== undefined && formData.value.addonKind !== null&& formData.value.addonKind !== '') {
      const addonKindVal = Number(formData.value.addonKind);
      console.log(addonKindVal,'addonKindVal')
      if (addonKindVal === 0) {
        err = "商品加料种类不能为0"
      }
    }

    for (const item of feedingList.value) {
      if (item.num !== '' && item.num !== undefined && item.num !== null) {
        const numVal = Number(item.num);
        if (numVal === 0) {
          err = "商品加料份数不能为0"
        }
      }
    }
    if (err) {
      uni.showToast({
        title: err,
        duration: 2000,
        icon: 'none',
      })
    } else {
      currentStep.value = 2
    }
  }
  const submitReq = async () => {

    uni.showLoading({
      title: '加载中...',
      mask: true,
    })
    console.log(feedingList.value, 'feedingListfeedingList')
    console.log(attributeList.value, 'attributeListattributeList')
    console.log(specsRows, 'specsRows')
    let skus = convertToSkus();
    console.log('转换后的 skus：', skus);
    let attributes = []; //属性
    let addonForms = []; //加料
    attributeList.value.forEach(item => {
      item.attributeValue.forEach(attr => {
        attributes.push(Number(attr.definitionValueId));
      });
    });
    feedingList.value.forEach(item => {
      addonForms.push({
        id: item.id,
        name: item.name,
        num: item.num ? Number(item.num) : null
      });
    });
    console.log(attributes, 'attributes', addonForms, 'addonForms')
    let postData = JSON.parse(JSON.stringify(formData.value))
    postData.sortOrder = Number(postData.sortOrder) != 0 ? Number(postData.sortOrder) : undefined
    postData.productionTime = Number(postData.productionTime) != 0 ? Number(postData.productionTime) : undefined
    postData.addonKind = postData.addonKind ? Number(postData.addonKind) : null
    // postData.deliveryMethod = postData.deliveryMethod
    postData.mainImage = fileList1.value
      .map((item) => {
        return item.url
      })
      .join(',')
    postData.introImages = fileList2.value
      .map((item) => {
        return item.url
      })
      .join(',')
    postData.attributes = attributes
    postData.addonForms = addonForms
    postData.skus = skus
    console.log(postData, 'POSTPOST')
    const fn = spuId.value ? updateProducts : addProducts
    try {
      const res = await fn(postData)
      console.log(res, 'resres')
      uni.hideLoading()
      uni.showToast({
        title: res.Result || '',
        icon: 'success',
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 800)
    } catch (error) {
      console.log(error)
    }
  }
  const close = () => {
    uni.navigateBack()
  }

  function inputOver(e) {
    // 可以在此处获取到编辑器已编辑的内容
    formData.value.description = e.html
  }

  /**
   * 超出最大内容限制
   * @param {Object} e {html,text} 内容的html文本，和text文本
   */
  function overMax(e) {
    // 若设置了最大字数限制，可在此处触发超出限制的回调
    console.log('==== overMax :', e)
  }

  /** 编辑器就绪*/
  function initEditor(editor) {
    editorIns.value = editor
    preRender()
  }

  function preRender() {
    // 异步获取后端数据后，初始化编辑器内容
    editorIns.value.setContents({
      html: formData.value.description,
    })
  }

  //上传图片
  const upinImage = async (tempFiles, editorCtx) => {
    console.log(tempFiles, 'tempFiles')
    uni.showLoading({
      title: '加载中...',
      mask: true,
    })
    let res = await uploadImgApi({
      name: "",
      size: tempFiles[0].size,
      thumb: tempFiles[0].tempFilePath,
      type: tempFiles[0].fileType,
      url: tempFiles[0].tempFilePath,
    })
    if (res) {
      uni.hideLoading()
      editorCtx.insertImage({
        src: res.Result,
        width: '80%',
        success: function() {
          uni.hideLoading()
        }
      })
    }

  }

  //导出 - toolbar需要开启export工具
  function exportHtml(e) {
    uni.navigateTo({
      url: '/pages/out/out',
      success(res) {
        // 传至导出页面解析即可
        res.eventChannel.emit('e-transmit-html', {
          data: e,
        })
      },
    })
  }
</script>
<style lang="scss" scoped>
  .form-container {
    // padding: 0 100px;
  }

  .goods-container {
    background: #ffffff;
    border-radius: 10px;
    margin: 10px;

    .form-con {
      padding: 0 100px;

      :deep(.u-form-item__body__right__content__slot) {
        flex-direction: column !important;
        align-items: baseline !important;
      }

      .row-bot {
        :deep(.uni-row) {
          margin-bottom: 10px;
        }

        :deep(.is-disabled) {
          color: #666 !important;
          background: #F6F6F6 !important;
        }
      }

      .marg-col {
        :deep(.uni-col) {
          margin-bottom: 10px;
        }
      }

      .suffix-txt {
        background: #f5f6f8;
        border-left: 1px solid #e8ecef;
        font-weight: 400;
        font-size: 14px;
        color: #334681;
        padding: 6px 16px;
        box-sizing: border-box;
      }

      .suffix-num {
        font-weight: 400;
        font-size: 14px;
        color: rgba(51, 70, 129, 0.6);
        padding-right: 5px;
        box-sizing: border-box;
      }

      .specifications {
        background: #0f90fd;
        border-radius: 8px;
        font-weight: 400;
        font-size: 14px;
        color: #ffffff;
        padding: 7px 27px;
        box-sizing: border-box;
      }

      .spec-group {
        background: #f7f9fa;
        border-radius: 10px;
        border: 1px solid #e8ecef;
        padding: 10px 20px;
        box-sizing: border-box;
        margin-bottom: 10px;

        .del-btn {
          position: sticky;
          z-index: 99;

          :deep(.u-button) {
            float: right;
          }
        }
      }

      :deep(.u-button) {
        height: 32px;
        width: 100px;
        margin-left: 10px;
      }

      .generate-btn {
        display: flex;
        justify-content: center;
        margin: 17px 0;
      }

      .goods-name {
        font-weight: 400;
        font-size: 14px;
        color: #333333;
        margin-bottom: 4px;
      }
    }

    .form-det {
      display: flex;

      .tit {
        width: 100px;
        color: #303133;
        font-size: 15px;
      }

      .editor-box {
        border: 1px solid #e8e8e8;
        width: 100%;
      }
    }

    .info-tit {
      font-weight: 500;
      font-size: 14px;
      color: #333333;
      line-height: 20px;
      padding-left: 57px;
      box-sizing: border-box;
    }

    .step-nav {
      display: flex;
      align-items: center;
      margin: 20px;
      justify-content: center;
    }

    .step-item {
      position: relative;
      padding: 0 20px;
      line-height: 32px;
      font-size: 14px;
      color: #333;
      background: #f5f5f5;
      transition: all 0.3s;
    }

    /* 激活状态样式 */
    .step-item.active {
      background: #0f90fd;
      color: #fff;
      border-color: #0f90fd;
    }

    /* 箭头实现：每个步骤（除最后一个）右侧生成箭头 */
    .step-item:not(:last-child)::after {
      content: '';
      position: absolute;
      top: 0;
      right: -16px;
      width: 0;
      height: 0;
      border-top: 16px solid transparent;
      border-bottom: 16px solid transparent;
      border-left: 16px solid #0f90fd;
      z-index: 2;
    }

    .step-item:not(.active)::after {
      border-left-color: #f5f5f5;
    }

    .step-item:first-child {
      border-top-left-radius: 6px;
      border-bottom-left-radius: 6px;
    }

    .step-item:last-child {
      border-top-right-radius: 6px;
      border-bottom-right-radius: 6px;
    }
  }

  .submit_btncon {
    background: #ffffff;
    box-shadow: 0px -2px 4px 0px rgba(51, 70, 129, 0.1);
    border-radius: 10px 10px 0px 0px;
    display: flex;
    padding: 13px 0;
    box-sizing: border-box;

    button {
      padding: 0 46px;
      height: 34px;
      box-sizing: border-box;
      border-radius: 8px;
      margin: 0 10px;

      &:after {
        border: none;
      }
    }

    .submit_btn {
      background: #0f90fd;
      font-weight: 400;
      font-size: 14px;
      color: #ffffff;
    }

    .submit_close {
      background: #eeeeee;
      font-weight: 400;
      font-size: 14px;
      color: #333333;
    }
  }

  /* 预览列表 */
  .preview-list {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    margin-top: 10px;
    width: 100%;
  }

  .preview-item {
    position: relative;
    /* 用于操作按钮绝对定位 */
    width: 60px;
    height: 60px;
  }

  .preview-img {
    width: 100%;
    height: 100%;
    border-radius: 4px;
  }

  /* 操作按钮：覆盖在图片底部 */
  .operate-bar {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    justify-content: space-around;
    padding: 5px 0;
  }

  .operate-icon {
    color: #fff;
    font-size: 12px;
  }
</style>
